package com.hongye.proprietary.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hongye.common.utils.JwtUtil;
import com.hongye.common.utils.PageUtils;
import com.hongye.common.utils.Query;
import com.hongye.common.utils.R;
import com.hongye.proprietary.config.MyRabbitConfig;
import com.hongye.proprietary.controller.vo.LoginVo;
import com.hongye.proprietary.dao.UserHomeDao;
import com.hongye.proprietary.entity.UserHomeEntity;
import com.hongye.proprietary.service.UserHomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Map;


@Service("userHomeService")
public class UserHomeServiceImpl extends ServiceImpl<UserHomeDao, UserHomeEntity> implements UserHomeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MyRabbitConfig myRabbitConfig;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    HttpSession session;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserHomeEntity> page = this.page(
                new Query<UserHomeEntity>().getPage(params),
                new QueryWrapper<UserHomeEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R sendMsg(String userPhone) {
        //判断手机号是否存在
        UserHomeEntity userHomeEntity = baseMapper.selectOne(new QueryWrapper<UserHomeEntity>().eq("user_phone", userPhone));
        if (userHomeEntity!=null){
            //防止 短信防刷
           if (redisTemplate.opsForValue().get(userPhone)!=null){
               return R.ok("短信发送频繁 请稍后再发");
           }
           return myRabbitConfig.sendMsg(userPhone);

        }
        return R.error("输入的手机号不存在 请重新输入");
    }

    //用户验证码登录
    @Override
    public R login(LoginVo loginVo) {
        if (loginVo.getUserPhone()!=null){
            Object s = redisTemplate.opsForValue().get(loginVo.getUserPhone());
            UserHomeEntity userHomeEntity = baseMapper.selectOne(new QueryWrapper<UserHomeEntity>().eq("user_phone", loginVo.getUserPhone()));
            //判断手机号是否正确
            if (s!=null){
                //判断验证码是否正确
                if (s.equals(loginVo.getVerification())){
                    String user = jwtUtil.createJWT(userHomeEntity.getUserId().toString(), userHomeEntity.getUserName(), "user");
                    //通过Session存入redis 实现全局Session
                    session.setAttribute("userlogin",userHomeEntity);
                    return R.ok().put("token",user);
                }
            }
            return R.error("验证码错误 请重新输入");
        }
        return R.error("手机号不能为空");
    }

}